import Vue from 'vue'
import Vuex from 'vuex'
import token from '@/utils/token.js';

Vue.use(Vuex)

const actions = {
	//通过请求后台去解析token
	async getUserInfo({
		commit
	}) {
		const currentToken = token.getToken()
		if (!currentToken) return false

		try {
			const res = await uni.request({
				url: '/health-api/med-front-user/userFront/getUserToToken',
				method: 'GET',
				data: {
					token: currentToken
				}
			})
			console.log(res)
			if (res.data.code === 1) {
				commit('SETUSERPASSWORD', res.data.data.userPassword)
				commit('SETUSERAVATAR', res.data.data.userAvatar)
				commit('SETUSERPHONENUMBER', res.data.data.userPhoneNumber)
				commit('SETUSERNAME', res.data.data.userName)
				commit('SETUSERID', res.data.data.userId)
				commit('SETUSERACCOUNT', res.data.data.userAccount)
				return true
			} else {
				// token 无效，清除并跳转登录
				token.removeToken()
				commit('CLEAR_USER_INFO')
				uni.reLaunch({
					url: '/pages/login/login'
				})
				return false
			}
		} catch (error) {
			console.error('请求失败:', error)
			return false
		}
	},

	setUserPassword(context, value) {
		context.commit("SETUSERPASSWORD", value);
	},

	setUserAvatar(context, value) {
		context.commit("SETUSERAVATAR", value);
	},

	setUerPhoneNumber(context, value) {
		context.commit("SETUSERPHONENUMBER", value);
	},

	setUserName(context, value) {
		context.commit("SETUSERNAME", value);
	},

	setUserId(context, value) {
		context.commit("SETUSERID", value);
	},

	setUserAccount(context, value) {
		context.commit("SETUSERACCOUNT", value)
	},
	clearUserInfo(context) {
		token.removeToken()
		context.commit('CLEAR_USER_INFO')
	},
	setAddressId(context, value) {
		context.commit("SERADDRESSID", value)
	}
}

const mutations = {

	SETUSERPASSWORD(state, value) {
		state.userPassword = value;
	},

	SETUSERAVATAR(state, value) {
		state.userAvatar = value;
	},

	SETUSERPHONENUMBER(state, value) {
		state.userPhoneNumber = value;
	},

	SETUSERNAME(state, value) {
		state.userName = value;
	},

	SETUSERID(state, value) {
		state.userId = value;
	},

	SETUSERACCOUNT(state, value) {
		state.userAccount = value;
	},
	CLEAR_USER_INFO(state) {
		state.userPhoneNumber = ''
		state.userName = ''
		state.userId = ''
		state.userAccount = ''
	},
	SERADDRESSID(state, value) {
		state.addressId = value;
	}
}

const state = {
	userPassword: null,
	userAvatar: null,
	userPhoneNumber: null,
	userName: null,
	userId: null,
	userAccount: null,
	addressId: null
}

const store = new Vuex.Store({
	actions,
	mutations,
	state
})

export default store;